var chartTrend
var graphTrend
var graphTrendLeft
var graphTrendRight
var graphTrendTop
var graphTrendBottom
var yAxisTrend
var yAxisTrend2
var xAxisTrend

var chartTrend_header = 5

var graphHeight

var chartTrend_width
var chartTrend_height
var chartTrend_left
var chartTrend_top

var chartRanking_width
var chartRanking_height
var chartRanking_left
var chartRanking_top

var chartRankingHeader
var chartRanking

var chartChange_width
var chartChange_height
var chartChange_left
var chartChange_top

var chartMap_width
var chartMap_height
var chartMap_left
var chartMap_top

var chartPie_width
var chartPie_height
var chartPie_left
var chartPie_top

var chartTrend_outer_topBottomPadding
var chartTrend_outer_leftRightPadding
var chartTrend_outer_width
var chartTrend_outer_height
var chartTrend_outer_left
var chartTrend_outer_top

var chartTrend_inner_topBottomPadding
var chartTrend_inner_leftRightPadding
var chartTrend_inner_width
var chartTrend_inner_height
var chartTrend_inner_left
var chartTrend_inner_top

var chartRanking_outer_topBottomPadding
var chartRanking_outer_leftRightPadding
var chartRanking_outer_width
var chartRanking_outer_height
var chartRanking_outer_left
var chartRanking_outer_top

var chartRanking_inner_topBottomPadding
var chartRanking_inner_leftRightPadding
var chartRanking_inner_width
var chartRanking_inner_height
var chartRanking_inner_left
var chartRanking_inner_top

var vpw = $(window).width()
var vph = $(window).height()

var colors

var map

class bindTotal {
    constructor(drawType) {
        this.idx = ['总确诊', '总康复', '总死亡'].indexOf(drawType)
    }
    lineColor() {
        if (this.idx == 0) return colors[0][3][9]
        else if (this.idx == 1) return colors[6][3][9]
        else if (this.idx == 2) return colors[0][0][9]
    }
    pointColor() {
        if (this.idx == 0) return colors[0][8][6]
        else if (this.idx == 1) return colors[6][8][6]
        else if (this.idx == 2) return colors[0][0][6]
    }
}

var labelTxtLengthLimit = 5
class ARU { // auxiliary rendering unit
    constructor(data, region, keyStart, color3, drawType) {
        [this.markersColor, this.lineColor, this.txtColor] = [color3[0], color3[1], color3[2]]
        // this.lineColor = colors[1]
        this.data = data
        console.log(data)
        this.region = region
        this.regionEnglish = data[0][2]
        this.continent = data[0][0]
        this.possessor = data[0][1]
        this.population = data[0][4]['pop']
        this.statMilestones = data[0][3]
        this.keyStart = keyStart

        this.drawData = []
        this.updateDrawData(drawType)
    }
    updateDrawData(drawType) {
        this.avail = true
        if (drawType == '总确诊') {
            for (let m = 1; m < this.data.length; m++) {
                this.drawData.push(this.data[m][5])
            }
            this.initPoints()
        } else if (drawType == '每十万人确诊数量') {
            if (this.data[0][4]['pop'] == -1) {
                this.avail = false
                return
            } else {
                for (let m = 1; m < this.data.length; m++) {
                    this.drawData.push(this.data[m][5] / this.data[0][4]['pop'] * 100000)
                }
            }
            this.initPoints()
        }
    }
    initPoints() {
        this.xL = []
        this.yL = []
        for (let k = 0; k < this.data.length - 1; k++) {
            // console.log(chartTrend_inner_left, chartTrend_inner_width, this.data[this.data.length - 1][0], k + this.keyStart)
            this.xL.push(chartTrend_inner_left + (chartTrend_inner_width) / (this.data[this.data.length - 1][0]) * (k + this.keyStart))
            this.yL.push(chartTrend_outer_bottomPadding * 2
                + (chartTrend_inner_height - chartTrend_inner_top) * (1 - this.drawData[k] / dataRange))
        }
        this._initPll()
        this._initMarkersLabel()
    }

    updatePoints(trY, trK) {
        var newXL = this.xL
        var newYL = []
        for (let k = 0; k < this.yL.length; k++) {
            newYL.push(trY + this.yL[k] * trK)
        }
        this._updatePll(newXL, newYL)
        this._updateMarkersLabel(newXL, newYL)
    }

    _initPll() {
        let points = ''
        for (let k = 0; k < this.yL.length; k++) {
            points += this.xL[k] + ',' + this.yL[k] + ' '
        }
        this.pll = graphTrend.append("polyline")
            .attr("class", "trendPll")
            .attr("stroke", this.lineColor)
            .attr('stroke-width', '2')
            .attr("fill", "none")
            .attr("points", points)
    }
    _initMarkersLabel() {
        this.markers = []
        console.log('IIIIIIII length', this.yL.length)
        for (let k = 0; k < this.yL.length; k++) {
            this.markers.push(
                graphTrend.append('circle')
                    .attr('class', 'trendMarkers')
                    .attr('fill', this.markersColor)
                    .attr('cx', this.xL[k])
                    .attr('cy', this.yL[k])
                    .attr('r', 2)
            )
        }
        this.label0 = chartRanking.append('text')
            .attr('class', 'regionNameLabel')
            .attr('text-anchor', 'start')
            // .text(this.region)
            .attr('transform', 'translate(' + String(61) + ', 5)')
            .attr('y', this.yL[this.yL.length - 1])
            .attr('fill', this.txtColor)
        
        for (let k = 0; k < Math.ceil(this.region.length / labelTxtLengthLimit); k++) {
            this.label0.append('tspan')
                .text(this.region.substring(k * labelTxtLengthLimit, k * labelTxtLengthLimit + labelTxtLengthLimit))
                .attr('x', 0)
                .attr('dy', k * 16)
                .attr('class', 'regionNameLabelSub' + this.region)
                .attr('lineSeq', k)
        }
        this.label = d3.selectAll('.regionNameLabelSub' + this.region)
        console.log("SELL", this.label)
        this.labelPointer = chartRanking.append('line')
            .attr('class', 'regionNameLabelPointer')
            .attr('x1', 0)
            .attr('x2', 60)
            .attr('y1', this.yL[this.yL.length - 1])
            .attr('y2', this.yL[this.yL.length - 1])

            .attr('stroke', this.txtColor)
            .attr('stroke-width', 1)
    }
    _updatePll(newXL, newYL) {
        let points = ''

        for (let k = 0; k < newYL.length; k++) {
            points += newXL[k] + ',' + newYL[k] + ' '
        }
        this.pll.attr('points', points)
    }
    _updateMarkersLabel(newXL, newYL) {
        console.log('EEE', this.label)
        for (let k = 0; k < newYL.length; k++) {
            this.markers[k].attr('cx', newXL[k])
                .attr('cy', newYL[k])
        }
        this.label.attr('y', newYL[newYL.length - 1])
        // for (let ts of this.label) {
        //     // console.log(ts)
        //     ts.setAttribute('dy', 8 * 5)
        // }
        this.labelPointer.attr('y1', newYL[newYL.length - 1])
            .attr('y2', newYL[newYL.length - 1])
    }
}

function sizeW(b0, b1, m) {
    // return 'calc(' + String(b1 - b0) + '%' + ' - ' + m + 'px)'
    return (b1 - b0) / 100 * vpw - m
}

function sizeH(b0, b1, m) {
    // return 'calc(' + String(b1 - b0) + '%' + ' - ' + m + 'px)'
    return (b1 - b0) / 100 * vph - m
}

function posW(b, m) {
    // return 'calc(' + String(b) + '%' + ' + ' + m + 'px)'
    return b / 100 * vpw + m
}

function posH(b, m) {
    return b / 100 * vph + m
}

function layout() {
    var vb0 = 0
    var vb1 = 50
    var vb1_1 = 50
    var vb1_2 = 70
    var vb2 = 50
    var vb3 = 80

    var hb0 = 50
    var hb1 = 100
    var hb2 = 0
    var m = 5

    chartTrend_width = sizeW(vb0, vb2, m)
    chartTrend_height = sizeH(hb2, hb0, m)
    chartTrend_left = posW(vb0, m)
    chartTrend_top = posH(hb2, m)
    $('#map')
        .css('position','absolute')
        .css('width', chartTrend_width)
        .css('left', chartTrend_left)
        .css('height', chartTrend_height)
        .css('top', chartTrend_top)
    chartTrend_left = posW(vb1, m)
    $('#user-options-panel')
        .css('left', chartTrend_left)
    // 3 parts of chartTrend
    chartTrend_width = sizeW(vb0, vb1, m * 1)
    chartTrend_height = sizeH(hb0, hb1, m * 2)
    chartTrend_left = posW(vb0, m)
    chartTrend_top = posH(hb0, m)


    // 3 parts of chartTrend
    chartTrend_width = sizeW(vb0, vb1, m * 1)
    chartTrend_height = sizeH(hb0, hb1, m * 2)
    chartTrend_left = posW(vb0, m)
    chartTrend_top = posH(hb0, m)
    $('#chart-cont-trend')
        .css('width', chartTrend_width)
        .css('left', chartTrend_left)
        .css('height', chartTrend_height)
        .css('top', chartTrend_top)

    // chartTrend part 1
    chartTrend_outer_bottomPadding = 5
    chartTrend_outer_topPadding = chartTrend_header
    chartTrend_outer_topBottomPadding = 5

    chartTrend_outer_leftRightPadding = 5
    chartTrend_outer_width = chartTrend_width * 1 - 1 * chartTrend_outer_leftRightPadding
    chartTrend_outer_height = chartTrend_height - chartTrend_outer_topPadding - chartTrend_outer_bottomPadding
    chartTrend_outer_left = chartTrend_outer_leftRightPadding
    chartTrend_outer_top = chartTrend_outer_topPadding

    chartTrend_inner_topPadding = 5
    chartTrend_inner_bottomPadding = 30
    chartTrend_inner_leftPadding = 50
    chartTrend_inner_rightPadding = 5
    chartTrend_inner_width = chartTrend_outer_width - chartTrend_inner_leftPadding
    chartTrend_inner_height = chartTrend_outer_height - chartTrend_inner_topPadding - chartTrend_inner_bottomPadding
    chartTrend_inner_left = chartTrend_inner_leftPadding * 1
    chartTrend_inner_top = chartTrend_inner_topPadding * 1

    console.log(chartTrend_inner_left)
    // $('#chart-trend')
    //     .css('width', chartTrend_outer_width)
    //     .css('left', chartTrend_outer_left)
    //     .css('height', chartTrend_outer_height)
    //     .css('top', chartTrend_outer_top)


    graphTrendLeft = chartTrend_inner_left + chartTrend_outer_left
    graphTrendRight = chartTrend_width - chartTrend_outer_left * 2 - chartTrend_inner_left
    graphTrendTop = chartTrend_inner_top + chartTrend_outer_top + 0
    graphTrendBottom = graphTrendTop + chartTrend_inner_height - chartTrend_inner_top
    $('#graph-trend')
        .css('width', chartTrend_outer_width)
        .css('left', chartTrend_outer_left)
        .css('height', chartTrend_outer_height - chartTrend_inner_bottomPadding)
        .css('top', chartTrend_outer_top)

    $('#yAxis-trend')
        .css('width', chartTrend_outer_width)
        .css('left', chartTrend_outer_left)
        .css('height', chartTrend_outer_height - chartTrend_inner_bottomPadding + 10)
        .css('top', chartTrend_outer_top - 5)

    $('#xAxis-trend')
        .css('width', chartTrend_outer_width)
        .css('left', chartTrend_outer_left)
        .css('height', chartTrend_outer_height)
        .css('top', chartTrend_outer_top)

    // .css('width', chartTrend_outer_width)
    // .css('left', chartTrend_inner_left + chartTrend_outer_left)
    // .css('height', chartTrend_outer_height - chartTrend_inner_bottomPadding + chartTrend_outer_top)
    // .css('top', chartTrend_inner_top + chartTrend_outer_top + chartTrend_inner_height - chartTrend_inner_top)
    graphHeight = chartTrend_outer_height - chartTrend_inner_bottomPadding

    chartTrend = d3.select('#chart-trend')
    graphTrend = d3.select('#graph-trend')

    // chartTrend part 2
    chartRanking_outer_topBottomPadding = 10
    chartRanking_outer_leftRightPadding = 10
    chartRanking_outer_width = chartTrend_width * 0.75 - chartRanking_outer_leftRightPadding * 2
    chartRanking_outer_height = chartTrend_height - chartTrend_outer_topPadding - chartTrend_outer_bottomPadding
    chartRanking_outer_left = chartTrend_outer_leftRightPadding + chartTrend_outer_width
    chartRanking_outer_top = chartTrend_outer_topPadding

    chartRanking_inner_topPadding = 5
    chartRanking_inner_bottomPadding = 25
    chartRanking_inner_leftPadding = 30
    chartRanking_inner_rightPadding = 5
    chartRanking_inner_width = chartTrend_outer_width - chartRanking_inner_leftPadding - chartRanking_inner_rightPadding
    chartRanking_inner_height = chartTrend_outer_height - chartRanking_inner_topPadding - chartRanking_inner_bottomPadding
    chartRanking_inner_left = chartRanking_inner_leftPadding * 1
    chartRanking_inner_top = chartRanking_inner_topPadding * 1

    $('#chart-ranking')
        .css('width', chartRanking_outer_width)
        .css('left', chartRanking_outer_left)
        .css('height', chartRanking_outer_height)
        .css('top', chartRanking_outer_top)

    // $('#chart-ranking-header')
    //     .css('width', chartRanking_outer_width - 200)
    //     .css('left', chartRanking_outer_left + 160)
    //     // .css('height', chartTrend_header + 150)
    //     .css('top', 30)
    chartRanking = d3.select('#chart-ranking')

    crcInterval = [56, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72, 72]
    crcLeft = 90
    crcCt = 0
    $('.crc').each(function () {
        $(this).css('left', crcLeft)
            .css('top', 10)
        crcLeft += crcInterval[crcCt]
        crcCt += 1
    })

    chartPie_width = sizeW(vb2, vb3, m * 2)
    chartPie_height = sizeH(hb0, hb2, m)
    chartPie_left = posW(vb2, m)
    chartPie_top = posH(hb0, m)

    chartMap_width = sizeW(vb2, vb3, m * 2)
    chartMap_height = sizeH(hb2, hb1, m * 2)
    chartMap_left = posW(vb2, m)
    chartMap_top = posH(hb2, m)

    $('#chart-cont-map')

        .css('width', chartMap_width)
        .css('left', chartMap_left)

        .css('height', chartMap_height)
        .css('top', chartMap_top)

    $('#chart-cont-pie')
        .css('width', chartPie_width)
        .css('left', chartPie_left)

        .css('height', chartPie_height)
        .css('top', chartPie_top)

        .attr('visibility', 'hidden')
}

function initChart1() {
    selectorWidth1 = 240; selectorWidth2 = 190
    selectorTop0 = 10; selectorTop1 = 60; selectorTop2 = 145; selectorTop3 = 230
    selectorLeft1 = 10; selectorLeft2 = 250

    $('#chart-cont-pie').css('max-height', chartPie_height)

    $('#selector-mode-title').css('position', 'absolute')
        .css('left', selectorLeft1)
        .css('width', selectorWidth1)
        .css('top', selectorTop0)
    $('#selector-var-title').css('position', 'absolute')
        .css('left', selectorLeft2)
        .css('width', selectorWidth2)
        .css('top', selectorTop0)
    $('#region-selector').css('position', 'absolute')
        .css('left', selectorLeft1)
        .css('width', selectorWidth1)
        .css('top', selectorTop1)
    $('#ranking-selector').css('position', 'absolute')
        .css('left', selectorLeft1)
        .css('width', selectorWidth1)
        .css('top', selectorTop2)
    $('#sum-selector').css('position', 'absolute')
        .css('left', selectorLeft2)
        .css('width', selectorWidth2)
        .css('top', selectorTop1)
    $('#change-selector').css('position', 'absolute')
        .css('left', selectorLeft2)
        .css('width', selectorWidth2)
        .css('top', selectorTop2)
    $('#per100000-selector').css('position', 'absolute')
        .css('left', selectorLeft2)
        .css('width', selectorWidth2)
        .css('top', selectorTop3)

    // chartTrend y-axis
    var translate_yAxis = 'translate(' + chartTrend_inner_left + ',' + '0' + ')'

    var yScale = d3.scaleLinear()
        .domain([dataRange, 0])
        .range([0, chartTrend_outer_height - chartTrend_inner_bottomPadding])

    var yAxisTrend_tick2 = d3.axisRight(yScale)
        .ticks(20)

    yAxisTrend2 = d3.select('#chart-ranking')//.select('#graph-trend')
        .append("g")
        .attr("class", "axisY")
        .call(yAxisTrend_tick2)

    var yAxisTrend_tick = d3.axisLeft(yScale)
        .ticks(20)

    yAxisTrend = d3.select('#graph-trend')
        .append("g")
        .attr("class", "axisY")
        .attr("transform", translate_yAxis)
        .call(yAxisTrend_tick)
    d3.select('#chart-ranking').selectAll('.axisY')
        .attr('color', '#787878')

    d3.select('#graph-trend').selectAll('.axisY .tick')
        .each(function () {
            stroke = $(this).children('line').attr('stroke')
            d3.select(this)
                .append('line')
                .attr('class', 'gratlinesY')
                .attr('x2', chartTrend_inner_width)
                .attr('stroke', '#b6b6b6')
                .attr('stroke-dasharray', '3 3')
        })
    d3.selectAll("#chart-trend > g.axisY")
        .each(function () {
            d3.select(this)
                .style("font-size", "16px")
        })
    // chartTrend x-axis
    var translate_xAxis = 'translate(' + chartTrend_inner_left + ',' + (chartTrend_inner_height + 6) + ')'
    var translate_xTicks = 'translate(-16, 8.5) rotate(-35)'

    var xScale = d3.scaleTime()
        .domain([new Date("2020, 1, 22"), new Date("2020, 4, 29")])
        .range([0, chartTrend_inner_width])

    var xAxisTrend_tick = d3.axisBottom(xScale)
        .tickArguments([d3.timeDay.every(1)])
        .tickFormat(d3.timeFormat("%m-%d"))

    xAxisTrend = d3.select('#xAxis-trend')
        .append("g")
        .attr("class", "axisX")
        .attr("transform", translate_xAxis)
        .call(xAxisTrend_tick)

    d3.selectAll("#graph-trend > g")
        .each(function () {
            d3.select(this)
                .style("font-size", "12px")
        })

    $('#chart-ranking > g')
        .each(function () {
            d3.select(this)
                .style('font-size', '12px')
                .style('font-weight', 'normal')
        })
    ct = 0
    d3.selectAll(".axisX .tick")
        .each(function () {
            $(this).children('text').attr('transform', translate_xTicks)
                .attr('style', 'font-size:10px')
            ct += 1
            if (ct % 2 == 0) {
                $(this).children('text').attr('visibility', 'hidden')
            }
        })

    d3.selectAll('.axisX .tick')
        .each(function () {
            stroke = $(this).children('line').attr('stroke')
            d3.select(this)
                .append('line')
                .attr('class', 'gratlinesX')
                .attr('y2', -chartTrend_inner_height)
                .attr('stroke', '#b6b6b6')
                .attr('stroke-dasharray', '3 3')
        })
    // chartTrend inner chart

    var graphTrend_zoom = d3.zoom()
        .scaleExtent([1, 20000000000])
        .translateExtent([[0, 0], [0, chartTrend_outer_height - chartTrend_inner_bottomPadding]])
        .on('zoom', function () {
            tr = d3.event.transform
            var newY = tr.rescaleY(yScale);

            // update axes with these new boundaries
            yAxisTrend.call(
                d3.axisLeft(newY)
                    .ticks(20)
            )
            yAxisTrend2.call(
                d3.axisRight(newY)
                    .ticks(20)
            )
            $('.gratlinesY').remove()
            d3.select('#graph-trend').selectAll('.axisY .tick')
                .each(function () {
                    stroke = $(this).children('line').attr('stroke')
                    text = $(this).children('text').innerText
                    d3.select(this)
                        .append('line')
                        .attr('class', 'gratlinesY')
                        .attr('x2', chartTrend_outer_width - chartTrend_outer_left)
                        .attr('stroke', '#b6b6b6')
                        .attr('stroke-dasharray', '3 3')
                })
            for (aru of arus) {
                aru.updatePoints(tr.y, tr.k)
            }
            // for (i = 0; i < lines.length; i++) {
            //     var newPts = ''
            //     for (k = 0; k < yLL[i].length; k++) {
            //         newPts += xLL[i][k] + ',' + String(tr.y + parseFloat(yLL[i][k]) * tr.k) + ' '
            //     }
            //     lines[i].attr('points', newPts)
            // }
            // for (i = 0; i < markers.length; i++) {
            //     markers[i].attr('cy', String(tr.y + parseFloat(yLL2[i]) * tr.k))
            // }
            // for (i = 0; i < lines.length; i++) {
            //     labels[i].attr('y', String(tr.y + parseFloat(yL3[i]) * tr.k))
            // }
            // for (i = 0; i < lines.length; i++) {
            //     ranking[i].attr
            // }
        })
    graphTrend.call(graphTrend_zoom)
}

function translate1(k) {
    console.log('translate(' + chartTrend_outer_left + ',' + (chartTrend_outer_height - chartTrend_inner_bottomPadding + chartTrend_outer_top) + ')')
    return 'translate(' + chartTrend_outer_left + ',' + (-(chartTrend_outer_height - chartTrend_inner_bottomPadding + chartTrend_outer_top)) + ')'
}

var color = ['#']
var lines = []
var markers = []
var rects_sick = []
var rects_addCured = []
var rects_addDead = []
var rects_addConfirmed = []
var labels = []; var ranking = []
var xLL = []; var yLL = []; var yLL2 = []
var yL3 = []
var cL3 = []
var ranks = []
var ranksContent = []

var dataRange = 1200000
var ct = 0

var arus = []

function getColor(seq) {
    return [colors[seq][6][6], colors[seq][7][9], colors[seq][9][7]]
}

function userSelection(val) {

    compileData(val)
}

function compileData(val) {
    for (aru of arus) delete aru
    arus = []

    var drawType = '总确诊'
    // var drawType = '每十万人确诊数量'
    console.log('ALLLLL', (Object.entries(val[1])))
    for (let [k, v] of Object.entries(val[1])) {
        ct += 1
        ptLnTx_color = getColor(ct % 20)
        // drawData, drawRegion, keyStart, color
        thisAru = new ARU(v, k, v[1][0], ptLnTx_color, drawType)
        if (thisAru.avail == true) {
            arus.push(thisAru)
        }
    }
}

var typeBinded = new bindTotal('总康复')

function drawPll(lineColor, pointColor, keyStart, drawData, drawRegion, drawType) {
    var thisARU = new ARU(drawData, drawRegion, keyStart)
}
// console.log(thisARU.pll())
// var xL = []; var yL = []
// console.log('drawdata', drawData)
// for (k = keyStart; k < keyNum; k++) {
//     x = String(chartTrend_inner_left + (chartTrend_inner_width) / (keyNum - 1) * k)
//     y = String(chartTrend_outer_bottomPadding * 2 + (chartTrend_inner_height - chartTrend_inner_top) * (1 - drawData[k - keyStart][5] / dataRange))
//     xL.push(x)
//     yL.push(y)
//     yLL2.push(y)
// }
// xLL.push(xL)
// yLL.push(yL)
// var points = ''

// for (k = keyStart; k < keyNum; k++) {
//     points += xL[k - keyStart] + ',' + yL[k - keyStart] + ' '
// }

// lines.push(
//     graphTrend.append("polyline")
//         .attr("class", "trendPll")
//         .attr("stroke", lineColor)
//         .attr('stroke-width', '3')
//         .attr("fill", "none")
//         .attr("points", points)
//         .attr("style", "z-index:100")
// )

// for (k = keyStart; k < keyNum; k++) {
//     markers.push(
//         graphTrend.append('circle')
//             .attr('class', 'trendMarkers')
//             .attr('fill', pointColor)
//             .attr('cx', xL[k])
//             .attr('cy', yL[k])
//             .attr('r', 3)
//     )

//     if (k == keyNum - 1) {
//         yL3.push(yL[k])
//         cL3.push([drawData[i], drawRegion[i]])

//         let thisLabel = graphTrend.append('text')
//             .attr('class', 'cityLabel')
//             .text(drawRegion + drawType)
//             .attr('transform', 'translate(' + String(chartTrend_outer_width - 98) + ', -5)')
//             .attr('y', yL[k])
//             .attr('fill', 'rgb(0,0,0)')

//         labels.push(
//             thisLabel
//         )

//     }
// }

function drawDaily() {

}

function loadColors() {
    $.ajax({
        url: 'data/colors20.json',  //服务端接口地址
        type: "get",
        dataType: "json",
        async: true,
        success: function (result) {
            colors = result['colors']
        }
    })
}
function setGraticule(map, path) {
    var graticule = d3.geoGraticule()
        .step([10, 10]) //place graticule lines every 5 degrees of longitude and latitude
        .extent([[-180, -90], [181, 91]])

    //create graticule lines
    gratLines = map.selectAll(".gratLines") //select graticule elements that will be created
        .data(graticule.lines()) //bind graticule lines to each element to be created
        .enter() //create an element for each datum
        .append("path") //append each element to the svg as a path element
        .attr("class", "gratLines") //assign class for styling
        .attr("d", path) //project graticule lines
}
var contourf_svg
var provinces_svg
var cities_svg
var map2

var widthLambert = window.innerWidth * 0.5,
    heightLambert = window.innerHeight * 0.5
var projection = d3.geoWagner()
    // .parallels([20, 50])
    // .rotate([-150, 0])
    .scale(145)
    .center([5, 10])

    .translate([widthLambert / 2, heightLambert / 2]);
var path = d3.geoPath()
    .projection(projection);
var map2Transf

function initMap() {
    map2 = d3.select('#map')
    var promises = [];
    promises.push(d3.json("data/world.topojson")); //load choropleth spatial data
    Promise.all(promises).then(callback);

    function callback(data) {
        var worldAll = data[0]

        setGraticule(map2, path)

        var worldCountries = topojson.feature(worldAll, worldAll.objects.world).features
        console.log('map data', worldCountries, map2, path)
        provinces_svg = map2.selectAll()
            .data(worldCountries)
            .enter()
            .append("path")
            .attr("class", function (d) {
                console.log('classing', d)
                return "country " + d.properties.chinese_name;
            })
            .attr('fill-opacity',0)
            .attr('stroke-width',0.4)
            .attr('stroke','#000000')
            .attr("d", path)
        console.log('added', provinces_svg)
    }

    var zoom = d3.zoom()
        .on("zoom", function () {
            map2Transf = d3.event.transform
            gratLines.attr("transform", d3.event.transform)
            provinces_svg.attr('transform', d3.event.transform)
            // countries_svg.attr("transform", d3.event.transform)
        })
    console.log('un??', map2, zoom)
    map2.call(zoom)
    return map2
}

(function () {
    layout()
    initChart1()
    map = initMap()

    var titleVar = new Vue({
        el: '#selector-var-title',
        data: {
            prompt: ''
        }
    })

    loadColors()

    p1 = new Promise((resolve1, reject1) => {
        $.ajax({
            url: 'data/all2.topojson',
            type: 'get',
            dataType: 'json',
            success: (res => resolve1(res)),
            error: ((obj, status, err) => resolve1({}))
            // complete: ((obj, status) => {
            //     if (status != 'error') {
            //         resolve1(obj.responseJSON)
            //     } else {
            //         resolve1({})
            //     }
            // })
        })
    })
    p2 = new Promise((resolve2, reject2) => {
        $.ajax({
            url: 'data/foreign_c_pop.json',
            type: 'get',
            dataType: 'json',
            // complete: ((obj, status) => { if (status != 'error') { resolve2(obj.responseJSON) } else { resolve2({}) } })
            success: (res => resolve2(res)),
            error: ((obj, status, err) => resolve2({}))
        })
    })

    Promise.all([p1, p2]).then(val => {
        userSelection(val)
    })
    // .catch(error => {
    //     console.error('errrrro', error.message)
    // })

    // axios.all([axios.get('data/all.topojson'), axios.get('data/foreign2.json')])
    //     .then(res => console.log('fetched!!!!!', res))
    //     .catch(err => console.error(err))

    $.ajax({
        url: 'data/all.topojson',  //服务端接口地址
        type: "get",
        dataType: "json",
        success: function (res) {
            $('.compare-mode').click(function () {
                titleVar.prompt = '选择你想对比的量（选择任意数量）：'
                if ($('.display-selector').prop('type') !== 'checkbox') {
                    $('.display-selector').prop('checked', false)
                }
                $('.display-selector').prop('type', 'checkbox')
            })
            $('.ranking-mode').click(function () {
                titleVar.prompt = '选择进行排名的量（选择其一）：'
                if ($('.display-selector').prop('type') !== 'radio') {
                    $('.display-selector').prop('checked', false)
                }
                $('.display-selector').prop('type', 'radio')
            })
            var drawData = []
            var drawRegion = []
            console.log('length of geom', res['objects']['combine_original_7']['geometries'].length)
            for (let i = 0; i < res['objects']['combine_original_7']['geometries'].length; i++) {
                if (res['objects']['combine_original_7']['geometries'][i]['properties']['admin-level'] == 'city'
                    && res['objects']['combine_original_7']['geometries'][i]['properties']['province'] == '湖北省'
                    && res['objects']['combine_original_7']['geometries'][i]['properties']['city'] == '武汉市') {
                    console.log(i, res['objects']['combine_original_7']['geometries'][i]['properties']['city'])
                    drawData.push(res['objects']['combine_original_7']['geometries'][i]['properties'])
                    drawRegion.push(res['objects']['combine_original_7']['geometries'][i]['properties']['city'].replace('神农架林区', '神农架').replace('恩施土家族苗族自治州', '恩施州'))
                }
            }

            // let drawType = ['总确诊', '总死亡', '总康复', 'addConfirmed', 'addCured', 'addDead', 'sick']
            // lines = []
            // markers = []
            // labels = []
            // xLL = []
            // yLL = []
            // yL3 = []
            // cL3 = []
            // for (let h = 0; h < drawType.length; h++) {
            //     drawGraph(drawData, drawRegion, drawType[h])
            // }
        }
    })

    // initChart()
})()